﻿$(document).ready(function () {
    function to2DimentionalArray(viewModel)
    {
        var output = '';
        for (var row = 0; row < viewModel.rowsCount; row++) {
            var innerArr = new Array(viewModel.colsCount);

            for (var col = 0; col < viewModel.colsCount; col++) {
                innerArr[col] =  viewModel.rows()[row].cells()[col].state();
            }
            output += ko.toJSON(innerArr) + ';';
        }
        return output;
    }

    function Cell(state) {
        var self = this;
        self.state = ko.observable(state);
        self.invertState = function () {
            var currentState = self.state();
            self.state(currentState == 1?0:1);
        };

        return self;

    }

    function Row(cols) {
        var self = this;
        self.cells = ko.observableArray();
        for (var col = 0; col < cols; col++) {
            self.cells.push(new Cell(0));
        }
        return self;
    }

    function FillMatrix(rows, cols, matrix) {
        var output = [];
        for (var row = 0; row < rows; row++) {
            var newRow = new Row(cols);            
            output.push(newRow);
        }

        if (matrix) {
            for (var row = 0; row < matrix.length; row++) {
                for (var col = 0; col < matrix[row].length; col++) {
                    output[row].cells()[col].state(matrix[row][col]);
                }                
            }
        }

        return output;
    }

    function ViewModel(cols, rows){
        var self = this;
        self.colsCount = cols;
        self.rowsCount = rows;
        self.title = ko.observable('mytitle');
        self.rows = ko.observableArray(FillMatrix(rows,cols));
        self.result = ko.observable();


        self.debugInfo = ko.computed(function () {
            return ko.toJSON(self.rows);
        });

        self.convert = function () {
            $.ajax({
                type: 'POST',
                url: '/Home/ConvertLevels/',
                data: {
                    table: to2DimentionalArray(self)
                },

                success: function (result) {
                    self.result(FillMatrix(self.rowsCount, self.colsCount, result.data));
                },
                dataType: 'json'
            });
        }
        return self;
    }

    var viewModel = new ViewModel(25, 25);
    ko.applyBindings(viewModel);

    $(".table").on("click", 'td', function (event) {
        var cell = ko.dataFor(event.srcElement);
        cell.invertState();
    });
});